//
//  MovieViewController.m
//  快乐一点通
//
//  Created by cjp on 16/7/16.
//  Copyright © 2016年 cjp. All rights reserved.
//

#import "MovieViewController.h"
#import "MovieTableViewCell.h"
#import "MovieModel.h"
#import "FXXPlayerTool.h"

#import <AFNetworking.h>
#import <MJRefresh.h>
#import <MJExtension.h>
#import <ZFPlayer.h>
#import <RESideMenu.h>

@interface MovieViewController ()<VideoCellDelegate>

@property(nonatomic,strong)NSMutableArray *movieArray;
/** 电影模型 */
@property(nonatomic,strong)MovieModel *movieModel;
/** 当加载下一页数据时需要使用这个参数 */
@property(nonatomic,copy)NSString *timestamp;
/** 上一次的请求参数 */
@property(nonatomic,strong)NSDictionary *params;

@property(strong,nonatomic)ZFPlayerView *playerView;

@end

static NSString *const MovieCellId = @"movie";

@implementation MovieViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];

    // 添加刷新控件
    [self setupRefresh];
    
    
}

- (void)setupView{
    self.navigationItem.title = @"影视资讯";
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MovieTableViewCell class]) bundle:nil] forCellReuseIdentifier:MovieCellId];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

}



#pragma mark ------- 添加刷新控件 ------------
- (void)setupRefresh{
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewMovie)];
    // 自动改变透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreMovie)];
    
    
}

#pragma mark ------- 上拉刷新 -------------
- (void)loadNewMovie{
    
    // 结束下拉
    [self.tableView.mj_footer endRefreshing];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    self.params = params;
    
    [[AFHTTPSessionManager manager]GET:MovieURLNEW parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {

        if (self.params != params) return ;
        // 存储timestamp
        self.timestamp = responseObject[@"timestamp"];

        self.movieArray = [MovieModel mj_objectArrayWithKeyValuesArray:responseObject[@"videos"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            // 结束刷新
            [self.tableView.mj_header endRefreshing];

        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.params != params)
            return;
        // 结束刷新
        [self.tableView.mj_header endRefreshing];
    }];
    
}

#pragma mark ------- 下拉加载 ----------
- (void)loadMoreMovie{
    
    // 结束上拉
    [self.tableView.mj_header endRefreshing];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    params[@"timestamp"] = self.timestamp;
    self.params = params;
    
    NSString *str = [MovieURL stringByAppendingFormat:@"%zd" , self.params];
    
    [[AFHTTPSessionManager manager]GET:str parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {

        if (self.params != params) return ;
        
        // 存储timestamp
        self.timestamp = responseObject[@"timestamp"];

        NSArray *newMovie = [MovieModel mj_objectArrayWithKeyValuesArray:responseObject[@"videos"]];
        [self.movieArray addObjectsFromArray:newMovie];
        
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
            // 结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.params != params) return ;
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
        
    }];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.tableView.mj_footer.hidden = (self.movieArray.count == 0);
    
    return self.movieArray.count;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait) {
        self.view.backgroundColor = GlobalBg;
    }else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        self.view.backgroundColor = [UIColor blackColor];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MovieTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MovieCellId forIndexPath:indexPath];
    
    cell.delegate = self;
    
    // 取到对应cell的model
    __block MovieModel *model  = self.movieArray[indexPath.row];
    cell.movie = self.movieArray[indexPath.row];
    
    __block NSIndexPath *weakIndexPath = indexPath;
    __block MovieTableViewCell *weakCell = cell;
    __weak typeof(self)weakSelf = self;
    // 点击播放的回调
    cell.playBlock = ^(UIButton *btn){
        weakSelf.playerView = [ZFPlayerView sharedPlayerView];
        // 设置player相关参数(需要设置imageView的tag值，此处设置的为101)
        [weakSelf.playerView setVideoURL:[NSURL URLWithString:model.first_url] withTableView:weakSelf.tableView
                             AtIndexPath:weakIndexPath
                        withImageViewTag:101];
        [weakSelf.playerView addPlayerToCellImageView:weakCell.playVideo];
        // 下载功能
        weakSelf.playerView.hasDownload   = YES;
        // 赋值分辨率字典
        
//         weakSelf.playerView.resolutionDic = dic;
        //（可选设置）可以设置视频的填充模式，默认为（等比例填充，直到一个维度到达区域边界）
        weakSelf.playerView.playerLayerGravity = ZFPlayerLayerGravityResizeAspect;
        // 自动播放
        [weakSelf.playerView autoPlayTheVideo];
        } ;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    MovieModel *model = self.movieArray[indexPath.row];

    return model.cellHeight;
}



// 页面消失时候
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.playerView resetPlayer];
}

@end
